var MaterialColorSettingDialog = function () {
  var template = /* html */ `
    <div class="material-color-setting-dialog" v-loading.fullscreen.lock="loading">
      <template v-if="isShow">
      <form-group group-title="显示列设置" style="margin-bottom:10px">
        <div class="has-line">
          <check-group has-width :data="showFields" :size="6"></check-group>
        </div>
      </form-group>

      <form-group group-title="物料类型设置" style="margin-bottom:10px">
        <div class="has-line table-setting" data-type="materialType">
          <el-table fit border :data="materialTypeFieldList" style="width:100%" empty-text="暂无物料类型配置数据">
            <el-table-column label="物料类型" min-width="140px" header-align="center" key="materialType">
              <template slot-scope="scope">
                <el-select filterable v-model="scope.row.materialType" size="mini" class="table-input">
                  <el-option v-for="item in materialTypeList" :key="item" :value="item"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="配置内容" min-width="500px" header-align="center" key="columns">
              <template slot-scope="scope">
                <check-group has-width :key="scope.row.id" :data="scope.row.columns" :size="5"></check-group>
              </template>
            </el-table-column>
            <el-table-column :resizable="false" label="操作" min-width="80px" align="center" key="handle">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" @click="delMaterialTypeConfig(scope.row)">删除</el-button>
              </template>
            </el-table-column>

            <template slot="append">
              <div class="add-row" :class="{'has-data':materialTypeFieldList.length>0}" :style="{width:materialTableWidth}"
                @click="addMaterialTypeConfig">
                <i class="el-icon-plus"></i>
                <span>新增物料类型配置</span>
              </div>
            </template>
          </el-table>
        </div>
      </form-group>

      <form-group group-title="老花镜设置" style="margin-bottom:10px">
        <div class="has-line">
          <check-group has-width :data="glassesFieldList" :size="6"></check-group>
        </div>
      </form-group>

      <form-group group-title="交期设置" style="margin-bottom:10px">
        <div class="has-line table-setting" data-type="delivery">
          <el-table fit border :data="deliveryDateFieldList" style="width:100%" empty-text="暂无交期配置数据">
            <el-table-column label="列数" width="100px" align="center" key="colIndex">
              <template slot-scope="scope">
                <span>{{scope.$index+1}}</span>
              </template>
            </el-table-column>
            <el-table-column label="配置内容" min-width="400px" header-align="center" key="columns">
              <template slot-scope="scope">
                <check-group has-width :key="scope.row.id" :data="scope.row.columns" :size="5"></check-group>
              </template>
            </el-table-column>
            <el-table-column :resizable="false" label="操作" min-width="80px" align="center" key="handle">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" @click="delDeliveryDate(scope.row)">删除</el-button>
              </template>
            </el-table-column>

            <template slot="append">
              <div class="add-row" :class="{'has-data':deliveryDateFieldList.length>0}" :style="{width:deliveryDateTableWidth}"
                @click="addDeliveryDate">
                <i class="el-icon-plus"></i>
                <span>新增交期配置</span>
              </div>
            </template>
          </el-table>
        </div>
      </form-group>

      <form-group group-title="其他设置" style="margin-bottom:10px">
        <div class="has-line">
          <el-form label-width="auto" size="small">
            <el-form-item label="物料颜色表高度">
              <el-input-number v-model="minHeight" :controls="false" :min="0" :precision="0" style="width:200px">
              </el-input-number>
              <div class="el-form-item__error">注：如果表格的总高度超过所填写的值，则会自适应表格内容</div>
            </el-form-item>
          </el-form>
        </div>
      </form-group>

      <div style="text-align:center;margin-bottom:10px">
        <el-button size="medium" type="primary" @click="ensure">保存</el-button>
      </div>
      </template>
    </div>
  `;

  return {
    props: {
      config: {
        type: Object,
        required: true
      }
    },

    data: function () {
      var materialColor = this.config.materialColor;
      return {
        loading: false,
        isShow: false,
        materialTableWidth: '100%',
        deliveryDateTableWidth: '100%',
        materialTypeList: [],
        showFields: [],
        materialTypeFieldList: [],
        deliveryDateFieldList: [],
        glassesFieldList: [],
        glassesTypeList: [],
        minHeight: materialColor.minHeight
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      Promise.all([
        this.setMaterialTypeList(),
        this.setGlassesTypeList()
      ]).then(function () {
        self.setShowFields();
        self.setGlassesFieldList();
        self.setMaterialTypeFieldList();
        self.setDeliveryDateFieldList();
        self.loading = false;
        self.isShow = true;
        self.tableWidthEvent();
      }).catch(function () {
        self.loading = false;
        self.isShow = true;
      });
    },

    methods: {
      setMaterialTypeList: function () {
        var self = this;
        return ajaxRequest('companyMaterialType/getCompanyMaterialTypeListByPage', {
          status: 1
        }, false).then(function (res) {
          var materialTypeList = res.returnData;
          materialTypeList = _.map(materialTypeList, 'materialType');
          self.materialTypeList = materialTypeList;
          return materialTypeList;
        });
      },

      setGlassesTypeList: function () {
        var self = this;
        return ajaxRequest('basicData/queryMaterialCompany', {
          view: 1,
          fullMaterialName: "老花镜"
        }, false).then(function (res) {
          var glassesList = res.returnData;
          var glassesTypeList = _.map(glassesList, 'materialType');
          glassesTypeList = _.uniq(glassesTypeList);
          glassesTypeList = _.orderBy(glassesTypeList, [function (str) {
            var num = parseInt(str);
            return num;
          }], ['asc']);
          self.glassesTypeList = glassesTypeList;
          return glassesTypeList;
        });
      },

      setShowFields: function () {
        var materialColor = this.config.materialColor;
        var fieldList = materialColor.fieldList;
        fieldList = _.map(fieldList, function (obj) {
          return {
            id: obj.id,
            label: obj.label,
            checked: obj.isShow,
            width: obj.width
          };
        });
        this.showFields = fieldList;
      },

      setGlassesFieldList: function () {
        var glassesConfig = this.config.materialColor.glassesConfig;
        var glassesTypeList = this.glassesTypeList;
        var glassesFieldList = [];
        for (var i = 0; i < glassesTypeList.length; i++) {
          var glassesType = glassesTypeList[i];
          var obj = glassesConfig[glassesType];
          var config = {
            id: glassesType,
            label: glassesType
          };
          if (obj === undefined) {
            config.checked = false;
            config.width = undefined;
          } else {
            config.checked = obj.isShow;
            config.width = obj.width;
          }
          glassesFieldList.push(config);
        }
        this.glassesFieldList = glassesFieldList;
      },

      setMaterialTypeFieldList: function () {
        var materialColor = this.config.materialColor;
        var materialTypeConfig = materialColor.materialTypeConfig;
        var materialTypeFieldList = [];
        var materialTypeAllFields = MaterialColorConfigModel.materialTypeFields;
        for (var i = 0; i < materialTypeConfig.length; i++) {
          var obj = materialTypeConfig[i];
          var materialType = obj.materialType;
          var columns = obj.columns;
          var columnGroup = _.groupBy(columns, 'id');
          var columnList = [];
          for (var j = 0; j < materialTypeAllFields.length; j++) {
            var fieldObj = materialTypeAllFields[j];
            var id = fieldObj.id;
            var columnObj = columnGroup[id];
            if (columnObj === undefined) {
              columnObj = {
                id: id,
                checked: false,
                width: undefined
              };
            } else {
              columnObj = _.cloneDeep(columnObj[0]);
              if (columnObj.width === undefined) {
                columnObj.width = undefined;
              }
              columnObj.checked = columnObj.isShow;
              delete columnObj.isShow;
            }
            columnObj.label = fieldObj.label;
            columnList.push(columnObj);
          }
          materialTypeFieldList.push({
            id: SysUtil.getId(),
            materialType: materialType,
            columns: columnList
          });
        }
        this.materialTypeFieldList = materialTypeFieldList;
      },

      setDeliveryDateFieldList: function () {
        var materialColor = this.config.materialColor;
        var deliveryDateConfig = materialColor.deliveryDateConfig;
        var deliveryDateFieldList = [];
        var deliveryDateFields = MaterialColorConfigModel.deliveryDateFields;
        for (var i = 0; i < deliveryDateConfig.length; i++) {
          var obj = deliveryDateConfig[i];
          var columns = obj.columns;
          var columnGroup = _.groupBy(columns, 'id');
          var columnList = [];
          for (var j = 0; j < deliveryDateFields.length; j++) {
            var fieldObj = deliveryDateFields[j];
            var id = fieldObj.id;
            var columnObj = columnGroup[id];
            if (columnObj === undefined) {
              columnObj = {
                id: id,
                checked: false,
                width: undefined
              };
            } else {
              columnObj = _.cloneDeep(columnObj[0]);
              if (columnObj.width === undefined) {
                columnObj.width = undefined;
              }
              columnObj.checked = columnObj.isShow;
              delete columnObj.isShow;
            }
            columnObj.label = fieldObj.label;
            columnList.push(columnObj);
          }
          deliveryDateFieldList.push({
            id: SysUtil.getId(),
            columns: columnList
          });
        }
        this.deliveryDateFieldList = deliveryDateFieldList;
      },

      addMaterialTypeConfig: function () {
        var materialTypeFieldList = this.materialTypeFieldList;
        var materialTypeFields = MaterialColorConfigModel.materialTypeFields;
        var columns = [];
        for (var i = 0; i < materialTypeFields.length; i++) {
          var obj = materialTypeFields[i];
          columns.push({
            id: obj.id,
            label: obj.label,
            checked: false,
            width: undefined
          });
        }

        materialTypeFieldList.push({
          id: SysUtil.getId(),
          materialType: '',
          columns: columns
        });
      },

      addDeliveryDate: function () {
        var deliveryDateFieldList = this.deliveryDateFieldList;
        var deliveryDateFields = MaterialColorConfigModel.deliveryDateFields;
        var columns = [];
        for (var i = 0; i < deliveryDateFields.length; i++) {
          var obj = deliveryDateFields[i];
          columns.push({
            id: obj.id,
            label: obj.label,
            checked: true,
            width: 100
          });
        }

        deliveryDateFieldList.push({
          id: SysUtil.getId(),
          columns: columns
        });
      },

      delMaterialTypeConfig: function (obj) {
        var materialTypeFieldList = this.materialTypeFieldList;
        var index = _.findIndex(materialTypeFieldList, {
          id: obj.id
        });
        if (index > -1) {
          materialTypeFieldList.splice(index, 1);
        }
      },

      delDeliveryDate: function (obj) {
        var deliveryDateFieldLis = this.deliveryDateFieldList;
        var index = _.findIndex(deliveryDateFieldLis, {
          id: obj.id
        });
        if (index > -1) {
          deliveryDateFieldLis.splice(index, 1);
        }
      },

      tableWidthEvent: function () {
        var self = this;
        this.$nextTick(function () {
          var $tableDiv = $(this.$el).find('.table-setting');
          for (var i = 0; i < $tableDiv.length; i++) {
            var $div = $($tableDiv[i]);
            var $table = $div.find('.el-table__header-wrapper table');
            $table.resize(function () {
              self.setTableWidth($div);
            });
            self.setTableWidth($div);
          }
        });
      },

      setTableWidth: function ($div) {
        var self = this;
        this.$nextTick(function () {
          var type = $div.data('type');
          var field = type === 'materialType' ? 'materialTableWidth' : 'deliveryDateTableWidth';
          var $table = $div.find('.el-table__header-wrapper table');
          var tableWidth = $table.width();
          if (tableWidth === null) {
            return;
          }
          self[field] = tableWidth + 'px';
        });
      },

      ensure: function () {
        if (!this.checkValid()) {
          return;
        }

        var materialColor = this.config.materialColor;
        materialColor.resetData({
          minHeight: this.minHeight,
          fieldList: this.showFields,
          materialTypeConfig: this.materialTypeFieldList,
          glassesConfig: this.glassesFieldList,
          deliveryDateConfig: this.deliveryDateFieldList
        });
        this.$emit('setting-success');
      },

      checkValid: function () {
        var showFields = this.showFields;
        showFields = _.filter(showFields, {
          checked: true
        });
        if (showFields.length === 0) {
          this.$alert('至少需要选择一列进行显示');
          return false;
        }
        for (var i = 0; i < showFields.length; i++) {
          var fieldObj = showFields[i];
          var width = fieldObj.width;
          if (width === undefined) {
            this.$alert(`请输入显示列'${fieldObj.label}'的宽度`);
            return false;
          }
        }

        var materialTypeFieldList = this.materialTypeFieldList;
        var materialTypeList = [];
        for (var i = 0; i < materialTypeFieldList.length; i++) {
          var material = materialTypeFieldList[i];
          var materialType = material.materialType;
          if (materialType === '') {
            this.$alert(`物料类型设置中，第${i+1}行未设置物料类型`);
            return false;
          }
          var columns = material.columns;
          for (var j = 0; j < columns.length; j++) {
            var columnObj = columns[j];
            if (columnObj.checked && columnObj.width === undefined) {
              this.$alert(`物料类型设置中，物料类型'${materialType}'的'${columnObj.label}'列未设置宽度'`);
              return false;
            }
          }
          materialTypeList.push(materialType);
        }
        var list = _.uniq(materialTypeList);
        if (materialTypeList.length !== list.length) {
          this.$alert('物料类型设置中，设置的物料类型有重复');
          return false;
        }

        var glassesFieldList = this.glassesFieldList;
        for (var i = 0; i < glassesFieldList.length; i++) {
          var glasses = glassesFieldList[i];
          if (glasses.checked && glasses.width === undefined) {
            this.$alert(`老花镜设置中，'${glasses.label}'列的宽度未设置`);
            return false;
          }
        }

        if (this.minHeight === undefined) {
          this.$alert('请输入物料颜色表高度');
          return false;
        }
        return true;
      }
    },

    components: {
      FormGroup: FormGroup,
      CheckGroup: CheckGroup
    },

    template: template
  };
}();
